#include<iostream>
#include<cstdio>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main()
{
    pid_t id=fork();
    if(id==0)
    {
       int count=10;
       while(count>0)
       {
            printf("我是子进程,pid为%d\n",getpid());
            count--;
            sleep(1);
       }
       exit(1);
    }
    else if(id>0)
    {
        int status=0;
        //非阻塞式等待一定要放在循环中
        while(1)
        {
            pid_t pid=waitpid(id,&status,WNOHANG); 
            if(pid<0)
            {
                printf("进程异常终止\n");
                break;
            }
            else if(pid==0)
            {
                printf("子进程还未退出,继续轮询\n");
                sleep(1);    //模拟父进程执行自己的任务
            }
            else 
            {
                printf("子进程正常退出,pid为:%d,退出码为:%d\n",pid,WIFEXITED(status));
                break;
            }
        }
    }
    return 0;
}

